<template>
    <div>
        <el-form ref="formRef" v-loading="loading" :model="formData" :rules="formRules" label-suffix=":"
                 label-width="120px">
            <div class="flex justify-start mr2">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="formData.roleName" placeholder="请输入角色名称"></el-input>
                </el-form-item>
                <el-form-item disabled label="角色编码" prop="roleCode">
                    <el-input v-model="formData.roleCode" disabled placeholder="请输入角色编码"></el-input>
                </el-form-item>
            </div>
            <el-form-item label="状态" prop="status">
                <el-switch v-model="formData.status"
                           :active-color="'#fff'"
                           :active-text="'启用'"
                           :active-value="1"
                           :inactive-color="'#000'"
                           :inactive-text="'停用'"
                           :inactive-value="0"
                           inline-prompt
                >
                </el-switch>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input v-model="formData.remark" placeholder="如：拥有管理用户的权限" style="width: 480px"
                          type="textarea"></el-input>
            </el-form-item>
            <el-form-item label="权限列表" prop="perms">
                <div style="height: 300px;width: 480px;">
                    <el-scrollbar>
                        <el-tree ref="treeRef" v-loading="loading" :data="treeData" :props="treeProps"
                                 default-expand-all
                                 node-key="id"
                                 show-checkbox style="max-width: 600px;background-color: whitesmoke"
                                 @check-change="handleCheckChange">
                        </el-tree>
                    </el-scrollbar>
                </div>
            </el-form-item>
            <el-form-item>
                <template #default>
                    <el-button type="primary" @click="submit">提交</el-button>
                    <el-button @click="cancel">取消</el-button>
                </template>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import {reactive, ref, unref, watch, onMounted} from "vue";
import {fetchPermissionList} from "@/composables/useSysPermission.js";
import instance from "@/api/request.js";
import {ElMessage} from "element-plus";

const loading = ref(false);

const props = defineProps(["data"])
const emit = defineEmits(["submit", "cancel"])

const formRef = ref()
const treeRef = ref();

const formData = ref({
    roleName: '',
    roleCode: '',
    status: 1,
    remark: '',
    perms: []
});
const treeData = ref([])

const treeProps = reactive({
        label: 'title',
        children: 'children',
    }
);
//
// onMounted(async () => {
//     treeData.value = await fetchPermissionList();
// })

const getAllLeafNodeIds = (nodes) => {
    const ids = [];
    const walk = (node) => {
        console.log(node)
        if (!node.children || node.children.length === 0) {
            ids.push(node.id);
        } else {
            node.children.forEach(walk);
        }
    };
    nodes.forEach(walk);
    return ids;
};

let leafNodeIds = [];
watch(
    () => props.data,
    async (newVal) => {
        if (!newVal) return;

        loading.value = true;
        treeData.value = await fetchPermissionList();

        // 初始化表单
        formData.value.roleName = newVal.roleName || '';
        formData.value.roleCode = newVal.roleCode || '';
        formData.value.status = newVal.status ?? 1;
        formData.value.remark = newVal.remark || '';

        const roleCode = newVal.roleCode;

        try {
            let permIds = [];

            if (roleCode) {
                const response = await instance.get('/role/perms', {params: {roleCode}});
                permIds = response.data || [];
            }

            if (leafNodeIds.length === 0 && treeData.value.length > 0) {
                leafNodeIds = getAllLeafNodeIds(treeData.value);
            }

            const leafOnlyIds = permIds.filter(id => leafNodeIds.includes(id));

            // 等待 DOM 更新，确保 tree 已渲染
            await nextTick(async () => {
                if (treeRef.value) {
                    treeRef.value.setCheckedKeys(leafOnlyIds);

                } else {
                    ElMessage.warning('treeRef is not available');
                }
            });
        } catch (error) {
            ElMessage.error('Failed to fetch permissions:', error);
            // 出错时清空选中
            await nextTick(() => {
                treeRef.value?.setCheckedKeys([]);
            });
        } finally {
            loading.value = false;
        }
    },
    {immediate: true}
);


const formRules = reactive({
    roleName: [
        {required: true, message: '请输入角色名称', trigger: 'blur'},
        {min: 2, max: 20, message: '角色名称长度在 2 到 20 个字符之间', trigger: 'blur'}
    ],
    roleCode: [
        {required: true, message: '请输入角色编码', trigger: 'blur'},
        {
            pattern: /^\w+$/,
            message: '角色编码只能包含字母、数字和下划线',
            trigger: 'blur'
        },
        {min: 3, max: 30, message: '角色编码长度在 3 到 30 个字符之间', trigger: 'blur'}
    ],
    remark: [
        {max: 200, message: '备注不能超过 200 个字符', trigger: 'blur'}
    ],
    perms: [
        {
            required: true,
            validator: (rule, value, callback) => {
                const checkedKeys = treeRef.value?.getCheckedKeys() || [];
                const halfCheckedKeys = treeRef.value?.getHalfCheckedKeys() || [];
                const hasPerms = checkedKeys.length > 0 || halfCheckedKeys.length > 0;
                if (!hasPerms) {
                    callback(new Error('请至少选择一个权限'));
                } else {
                    callback();
                }
            },
            trigger: 'change' // 注意：tree 的 change 不是 input，所以用 change 或自定义触发
        }
    ]
})

function submit() {
    // 手动触发表单验证
    formRef.value.validate(valid => {
        if (!valid) {
            ElMessage.error('请检查表单');
            return;
        }

        const perms = [
            ...treeRef.value.getCheckedKeys(),
            ...treeRef.value.getHalfCheckedKeys()
        ];

        const params = {
            ...unref(formData),
            perms
        };

        instance.post('/role/edit', params)
            .then(res => {
                ElMessage.success("修改完成");
                emit('submit'); // 刷新表格
            })
            .catch(err => {
                ElMessage.error(err.response?.data?.data?.message || '保存失败');
            });
    });
}

function cancel() {
    // formRef.value.resetFields()
    emit('cancel')
}

const loadNode = async (node, resolve) => {
    if (node.level === 0) {
        treeData.value = await fetchPermissionList();
        return resolve(treeData.value);
    }
    return resolve(node.data?.children || [])
}

const handleCheckChange = () => {
    nextTick(() => {
        // 触发表单对 perms 的校验（因为 el-tree 不触发 input/change）
        formRef.value?.validateField('perms');
    });
}
</script>